// 修改 ProductServiceImpl.java
package org.example.rubbish.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.rubbish.common.PageResult;
import org.example.rubbish.dto.ProductQuery;
import org.example.rubbish.entity.Product;
import org.example.rubbish.mapper.ProductMapper;
import org.example.rubbish.service.COSService;
import org.example.rubbish.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private COSService cosService;

    @Override
    public PageResult<Product> getProductList(ProductQuery query) {
        // 修复：确保 page 和 limit 有默认值
        if (query.getPage() == null || query.getPage() < 1) {
            query.setPage(1);
        }
        if (query.getLimit() == null || query.getLimit() < 1) {
            query.setLimit(10);
        }
        // 修复：正确的 offset 计算
        int offset = (query.getPage() - 1) * query.getLimit();
        query.setOffset(offset);

        List<Product> products = productMapper.selectProductList(query);
        Long total = productMapper.countProductList(query);

        // 使用正确的构造函数参数
        return new PageResult<>(query.getPage(), query.getLimit(), total, products);
    }

    @Override
    public Product getProductById(Long id) {
        return productMapper.selectById(id);
    }

    @Override
    @Transactional
    public void addProduct(Product product) {
        // 设置默认值
        if (product.getStatus() == null) {
            product.setStatus(0); // 默认下架
        }
        if (product.getStock() == null) {
            product.setStock(0);
        }
        if (product.getSortOrder() == null) {
            product.setSortOrder(0);
        }
        if (product.getIsDeleted() == null) {
            product.setIsDeleted(0);
        }

        productMapper.insert(product);
    }

    @Override
    @Transactional
    public void updateProduct(Product product) {
        Product existingProduct = productMapper.selectById(product.getId());
        if (existingProduct == null) {
            throw new RuntimeException("商品不存在");
        }

        // 如果更新了图片，删除旧的COS文件
        if (product.getImages() != null && !product.getImages().isEmpty() &&
                existingProduct.getImages() != null && !existingProduct.getImages().isEmpty()) {

            // 比较新旧图片，删除不再使用的图片
            List<String> newImages = product.getImages();
            List<String> oldImages = existingProduct.getImages();

            for (String oldImage : oldImages) {
                if (!newImages.contains(oldImage)) {
                        cosService.deleteFile(oldImage);
                }
            }
        }
        productMapper.update(product);
    }

    @Override
    @Transactional
    public void deleteProduct(Long id) {
        // 检查商品是否存在
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }

        // 检查是否有未完成订单
        if (!canDeleteProduct(id)) {
            throw new RuntimeException("该商品存在关联订单，无法删除");
        }

        // 删除COS上的图片文件
        if (product.getImages() != null && !product.getImages().isEmpty()) {
            for (String imageUrl : product.getImages()) {
                    cosService.deleteFile(imageUrl);
            }
        }
        productMapper.softDelete(id);
    }

    @Override
    @Transactional
    public void updateProductStatus(Long id, Integer status) {
        // 检查商品是否存在
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }

        if (!status.equals(0) && !status.equals(1)) {
            throw new RuntimeException("状态值不合法");
        }

        productMapper.updateStatus(id, status);
    }

    @Override
    public boolean canDeleteProduct(Long productId) {
        int activeOrderCount = productMapper.countActiveOrders(productId);
        return activeOrderCount == 0;
    }
}